package com.gitee.wsl.time.schedule.ext

import com.gitee.wsl.time.schedule.TimeScheduler
import com.gitee.wsl.time.schedule.collection.CollectionScheduler
import com.gitee.wsl.time.schedule.cron.CronDateTime
import com.gitee.wsl.time.schedule.cron.CronDateTimeScheduler
import com.gitee.wsl.time.schedule.cron.merge

/**
 * Create new one [CollectionKronScheduler] to include all [KronScheduler]s of [this] [Iterator]
 *
 * @see CollectionKronScheduler
 * @see CollectionKronScheduler.include
 */
fun Iterator<TimeScheduler>.merge(): CollectionScheduler {
    val cronDateTimes = mutableListOf<CronDateTime>()
    val collectionScheduler = CollectionScheduler()
    forEach {
        when (it) {
            is CronDateTimeScheduler -> cronDateTimes.add(it.cronDateTime)
            else -> collectionScheduler.include(it)
        }
    }
    if (cronDateTimes.isNotEmpty()) {
        collectionScheduler.include(CronDateTimeScheduler(cronDateTimes.merge()))
    }

    return collectionScheduler
}

/**
 * Create new one [CollectionKronScheduler] to include all [KronScheduler]s of [this] [Iterator]
 *
 * @see CollectionKronScheduler
 * @see CollectionKronScheduler.include
 */
@Suppress("NOTHING_TO_INLINE")
inline fun Iterable<TimeScheduler>.merge(): CollectionScheduler = iterator().merge()

/**
 * @return Vararg shortcut for [merge]
 */
@Suppress("NOTHING_TO_INLINE")
inline fun merge(vararg kronDateTimeSchedulers: TimeScheduler): CollectionScheduler = kronDateTimeSchedulers.iterator().merge()
